#!/usr/bin/python
#coding=utf-8

import uuid
from model.sessionstore import SessionStore 

class Session(object):
    def __init__(self, request, store=SessionStore()):
        self._data = {}
        self.request = request
        self.store = store 
        sid = request.get_cookies().get("sid")                                                               
        if sid:                                                                                            
            sid = sid.value                                                                         
        else:
            sid = None
        self.load(sid)

    def __contains__(self, name):
        return name in self._data 

    def __setitem__(self, name, value):
        self._data[name] = value

    def __getitem__(self, name):
        return self._data[name]

    def get(self, name):
        if self._data.has_key(name):
            return self._data[name]
        else:
            return None

    def load(self, sid = None):
        self.sid, self.new = sid, False
        if not self.sid:
            self.new = True
            self.sid = self.generate_sid()
        self._data = self.store.get(sid) or dict() 

    def save(self):
        self.store.set(self.sid, self._data)

    def generate_sid(self):
        sid = "".join(uuid.uuid4().hex for i in xrange(2))
        return sid

    def is_new(self):
        return self.new

    def invalidate(self):
        self.store.delete(self.sid)
